/*global window: false*/
/*
 * #depends subsonic-autodetect.js
 * #depends user-preferences-store.js
 */
Ext.ns('Ext.ux.mattgoldspink.subsonic');

Ext.ux.mattgoldspink.subsonic.Login = function(){
    Ext.state.Manager.setProvider(Ext.ux.mattgoldspink.subsonic.UserPrefsStore);

    if (Ext.state.Manager.get('u') === undefined || Ext.state.Manager.get('p') === undefined) {
        var loc = window.location;
        var baseAPIURL = loc.protocol + '//' + loc.host + Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/ping.view';
        if(Ext.ux.mattgoldspink.subsonic.desktopApp){
        	baseAPIURL = Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/ping.view';
        }
        var loginWindow = new Ext.Window({
            title: 'Login',
            closable:false,
            width:370,
            plain:true,
            plugins: ['msgbus'],
            items: [
                {
                    xtype: 'form',
                    labelWidth: 75,
                    bodyStyle:'padding:5px 5px 0',
                    width: 350,
                    defaults: {width: 230},
                    items: [
                        {
                            xtype: 'textfield',
                            name: 'apiurl',
                            fieldLabel: 'Detected API URL',
                            value: baseAPIURL,
                            disabled: true
                        },
                        {
                            xtype: 'textfield',
                            name: 'username',
                            fieldLabel: 'Enter your username',
                            allowBlank: false    
                        }, {
                            xtype: 'textfield',
                            inputType:'password',
                            name: 'password',
                            fieldLabel: 'Enter your password',
                            allowBlank: false,
                            enableKeyEvents: true,
                            listeners: {
                                specialkey: function(field, e){
                                    if (e.getKey() == e.ENTER) {
                                        var button = field.ownerCt.buttons[0];
                                        button.handler.call(button, button);
                                    }
                                }
                            }
                        }
                    ],
                    buttons: [{
                        text: 'Log in',
                        formBind: true,
                        handler: function(button){
                            var form = button.ownerCt.ownerCt.getForm(), values, username, password;
                            values = form.getValues();
                            username = values.username;
                            password = values.password;
                            Ext.MessageBox.show({
                               msg: 'Verifying your username and password',
                               progressText: 'Checking',
                               width:300,
                               wait:true,
                               waitConfig: {interval:200}
                               });
                               var params = {
                                   'u': username,
                                'p': 'enc:'+Ext.ux.mattgoldspink.subsonic.hexEncode(password)
                            };
                            Ext.apply(params, Ext.ux.mattgoldspink.subsonic.LoginDetails);
                            Ext.Ajax.request({
                               url: Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/ping.view',
                               success: function(response) {
                                    var status = response.responseData.status;
                                    var error = response.responseData.error;
                                    if (status === 'ok' && !Ext.isDefined(error)) {
                                           Ext.state.Manager.set('u', username);
                                        Ext.state.Manager.set('p', Ext.ux.mattgoldspink.subsonic.hexEncode(password));
                                        Ext.ux.mattgoldspink.subsonic.LoginDetails.u = Ext.state.Manager.get('u');
                                        Ext.ux.mattgoldspink.subsonic.LoginDetails.p = 'enc:'+Ext.state.Manager.get('p');
                                        Ext.MessageBox.hide();
                                        loginWindow.close();
                                        loginWindow.publish('subsonic.login.ok', Ext.ux.mattgoldspink.subsonic.LoginDetails);
                                    } else {
                                        Ext.MessageBox.hide();
                                        Ext.MessageBox.setIcon(Ext.MessageBox.ERROR);
                                        Ext.MessageBox.alert('Error code: '+response.responseData.error.code, 'There was an error logging in:<br/>'+response.responseData.error.message, function(){
                                           form.reset(); 
                                        });
                                    }                            
                               },
                               failure: Ext.ux.mattgoldspink.subsonic.Login,
                               params: params
                            });
                            
                        }
                    }]
                }
            ]
        }).show();
    } else {
        Ext.ux.mattgoldspink.subsonic.LoginDetails.u = Ext.state.Manager.get('u');
        Ext.ux.mattgoldspink.subsonic.LoginDetails.p = 'enc:'+Ext.state.Manager.get('p');
    }
};
